import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Input, Popconfirm, Modal, Tag, Alert, Message as msg} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, FIXED_COLUMN_WIDTH, FORM_ROW_OPTIONS} from '../constants';
import {PERMISSION, transportTypeOne, transportTypeNormal} from './constants';
import {hasPermissions} from './utils';
import {getDetail, getDealersQuickly, getDealers, partOrderPlanDetail, partReplacementQuery, getLastTime} from './api';
import {injectIntl, language} from './intl';
import {formatAmount, conventEnumValueToString} from '../utils';
import TextInput from 'Shared/components/TextInput';
import SearchInput from 'Shared/components/SearchInput';
import styles from './style.css';
import PartMultiSelectPanel from './PartMultiSelectPanel';
import PartOrderPlanPanel from './PartOrderPlanPanel';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import WrappedSelect from '../common/WrappedSelect';
import Return from '../common/Return';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import ImportPanel from './ImportPanel';
import {newOrUpdateOrderValidator} from './validator';
import {transportType, paymentType, partOrderPriceTerms, currency} from '../Enum';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import Export from '../common/Export';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';

const {Description} = DescriptionList;
const FormItem = Form.Item;
const transportTypeList = transportType.toList(language);
const transportTypeOneList = transportTypeOne.toList(language);
const transportTypeNormalList = transportTypeNormal.toList(language);
const paymentTypeList = paymentType.toList(language);
const partOrderPriceTermsList = partOrderPriceTerms.toList(language);
class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        showImportPanel: false,
        showPartMultiSelectPanel: false,
        showPartOrderPlan: false,
        details: [],
        isAlert: true,
        partOrderTypeCode: '',
        isLoading: false,
        isPartSaleOrder: true
    }

    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                            partOrderTypeCode: res.data.partOrderTypeName,
                            details: res.data.details.map(v => Object.assign({}, v, {
                                isDealerUser: this.props.isDealerUser,
                                price: v.price ? v.price : v.estimatedPrice,
                                quantity: v.stockQuantity
                            }))
                        });
                    else
                        this.setState(({
                            loading: false
                        }));
                });
        }
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    setRowClassName(record) {
        if(record.isColor)
            return styles.rowStyle;
        if(record.isType || record.isTransport)
            return styles.rowRedStyle;
        if(record.estimatedPrice && !record.isDealerUser)
            return styles.rowRedStyle;
    }
    getPartSaleOrder = data => {
        if(data.dealerId && data.brandId && data.transportType && data.partOrderTypeId && this.state.isPartSaleOrder && !data.id) {
            this.setState({loading: true});
            getLastTime({
                dealerId: data.dealerId,
                brandId: data.brandId,
                transportType: data.transportType,
                partOrderTypeId: data.partOrderTypeId,
            })
                .then(res => {
                    if(res.ok)
                        this.setState({
                            isPartSaleOrder: false,
                            loading: false,
                            data: Object.assign({}, data, {
                                customerOrderCode: data.customerOrderCode ? data.customerOrderCode : res.data.customerOrderCode,
                                paymentType: data.paymentType ? data.paymentType : res.data.paymentType,
                                partOrderPriceTerms: data.partOrderPriceTerms ? data.partOrderPriceTerms : res.data.partOrderPriceTerms,
                                carier: data.carier ? data.carier : res.data.carier,
                                receivedCompany: data.receivedCompany ? data.receivedCompany : res.data.receivedCompany,
                                receivedTelephone: data.receivedTelephone ? data.receivedTelephone : res.data.receivedTelephone,
                                receivedPerson: data.receivedPerson ? data.receivedPerson : res.data.receivedPerson,
                                receivedPersonPhone: data.receivedPersonPhone ? data.receivedPersonPhone : res.data.receivedPersonPhone,
                                receivedPort: data.receivedPort ? data.receivedPort : res.data.receivedPort,
                                shipmentPort: data.shipmentPort ? data.shipmentPort : res.data.shipmentPort,
                                remark: data.remark ? data.remark : res.data.remark,
                                receivedAddress: data.receivedAddress ? data.receivedAddress : res.data.receivedAddress,
                            })
                        });
                    else
                        this.setState(({
                            loading: false
                        }));
                });
        }
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onChangeSwitch = (value, name) => {
        if(name === 'partOrderTypeId') {
            const partSaleOrderType = this.props.initEnum.partSaleOrderTypes.find(v => v.value === value);
            // eslint-disable-next-line no-nested-ternary
            const transport = partSaleOrderType.text === 'VOR' ? transportType.快递
                : ((partSaleOrderType.text === 'Normal' || partSaleOrderType.text === 'Quarterly') ? transportType.海运 : null);
            const data = Object.assign({}, this.state.data, {
                [name]: value,
                transportType: transport
            });
            this.getPartSaleOrder({
                ...this.state.data,
                [name]: value,
                transportType: transport
            });
            this.setState({
                data,
                details: [],
                hasOperat: true,
                partOrderTypeCode: partSaleOrderType.text
            });
        } else {
            this.getPartSaleOrder({
                ...this.state.data,
                [name]: value
            });
            const data = Object.assign({}, this.state.data, {
                [name]: value
            });
            this.setState({
                data,
                details: [],
                hasOperat: true
            });
        }
    }
    onChangeSwitchBrand = (value, name) => {
        this.getPartSaleOrder({
            ...this.state.data,
            [name]: value
        });
        const data = Object.assign({}, this.state.data, {
            [name]: value,
            brandCode: this.props.initEnum.brands.find(v => v.value === value).text,
            dealerId: '',
            dealerCode: '',
            dealerName: '',
            country: '',
            currency: undefined
        });
        this.setState({
            data,
            details: [],
            hasOperat: true
        });
    }
    onChangePartOrderType = (value, name) => {
        const partSaleOrderType = this.props.initEnum.partSaleOrderTypes.find(v => v.value === value);
        // eslint-disable-next-line no-nested-ternary
        const transport = partSaleOrderType.text === 'VOR' ? transportType.快递
            : ((partSaleOrderType.text === 'Normal' || partSaleOrderType.text === 'Quarterly') ? transportType.海运 : null);
        if(this.state.details.length > 0 && this.state.data.partOrderTypeId !== undefined && this.state.data.partOrderTypeId !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch1',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switchPartOrderType',
                    defaultMessage: '变更订单类型，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitch(value, name)
            });
        else {
            this.getPartSaleOrder({
                ...this.state.data,
                [name]: value,
                transportType: transport
            });
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value,
                    transportType: transport
                }),
                hasOperat: true,
                partOrderTypeCode: partSaleOrderType.text
            });
        }
    }
    onChangeBrand = (value, name) => {
        this.getPartSaleOrder({
            ...this.state.data,
            [name]: value
        });
        if(this.state.details.length > 0 && this.state.data.brandId !== null && this.state.data.brandId !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch',
                    defaultMessage: '变更品牌，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitchBrand(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value,
                    brandCode: this.props.initEnum.brands.find(v => v.value === value).text
                }),
                hasOperat: true
            });
    }
    onChangeTransportType = (value, name) => {
        this.getPartSaleOrder({
            ...this.state.data,
            [name]: value
        });
        if(this.state.details.length > 0 && this.state.data.transportType !== null && this.state.data.transportType !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch3',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switchTransportType',
                    defaultMessage: '变更运输方式，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitch(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value
                }),
                hasOperat: true
            });
    }
    onSelectPartOrderPlan = records => {
        const retailDetails = this.state.details || [];
        partOrderPlanDetail(records.id)
            .then(res => {
                if(res.ok) {
                    res.data.details.forEach(r => {
                        const index = retailDetails.findIndex(v => v.partId === r.partId);
                        if(index === -1)
                            retailDetails.push({
                                partId: r.partId,
                                partCode: r.partCode,
                                partName: r.partName,
                                unit: r.unit,
                                planQuantity: r.n2Quantity,
                                price: r.price ? r.price : r.estimatedPrice,
                                minPackSize: r.minPackSize,
                                estimatedPrice: r.estimatedPrice,
                                quantity: r.stockQuantity,
                                partReplacementCode: r.partReplacementCode,
                                isType: r.isType,
                                isTransport: r.isTransport,
                                isDealerUser: this.props.isDealerUser
                            });
                    });
                    this.setState({
                        data: Object.assign({}, this.state.data, {
                            partOrderPlanId: records.id,
                            partOrderPlanCode: records.code
                        }),
                        details: [...retailDetails],
                        hasOperat: true,
                        showPartOrderPlan: false
                    });
                } else
                    this.setState(({
                        showPartOrderPlan: false
                    }));
            });
    }
    onClosePartMultiSelectPanel = () => {
        this.setState({showPartMultiSelectPanel: false});
    }
    onSelectPart = records => {
        const retailDetails = this.state.details || [];
        records.forEach(r => {
            const index = retailDetails.findIndex(v => v.partId === r.id);
            if(index === -1)
                retailDetails.push({
                    partId: r.id,
                    partCode: r.code,
                    partName: r.name,
                    unit: r.unit,
                    planQuantity: r.minPackSize,
                    price: r.price ? r.price : r.estimatedPrice,
                    minPackSize: r.minPackSize,
                    estimatedPrice: r.estimatedPrice,
                    quantity: r.quantity,
                    partReplacementCode: r.partReplacementCode,
                    isType: r.isType,
                    isTransport: r.isTransport,
                    isDealerUser: this.props.isDealerUser
                });
        });
        this.setState({
            details: [...retailDetails],
            hasOperat: true,
            showPartMultiSelectPanel: false,
            isAlert: true
        });
    }
    onClickPartOrderPlan = () => {
        if(!this.state.data.brandId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.brandId',
                defaultMessage: '请先选择品牌'
            }));
        if(!this.state.data.dealerId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.dealerId',
                defaultMessage: '请先选择总代'
            }));
        if(!this.state.data.partOrderTypeId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.partOrderTypeId',
                defaultMessage: '请先选择订单类型'
            }));
        if(!this.state.data.transportType)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.transportType',
                defaultMessage: '请先选择运输方式'
            }));
        this.setState({showPartOrderPlan: true});
    }
    onClosePartOrderPlan = () => {
        this.setState({showPartOrderPlan: false});
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true,
            isAlert: true
        });
    }
    onDeleteDetail = e => {
        const partId = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.partId !== partId);
        this.setState({
            details: [...tmp],
            hasOperat: true,
            isAlert: true
        });
    }
    
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {data, details} = this.state;
        const isValid = newOrUpdateOrderValidator(data, details);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data, details).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onUpdateQuantity = (planQuantity, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.partId === id) {
                if(planQuantity && d.minPackSize && !Number.isInteger(planQuantity / d.minPackSize))
                    msg.warn(this.props.intl.formatMessage({
                        id: 'newPanel.message.planQuantityMinPackSize',
                        defaultMessage: '备件最小包装数大于0时，备件清单的订货数量是最小包装数的整数倍'
                    }));
                return Object.assign({}, d, {
                    planQuantity,
                    isColor: false
                });
            }
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onClickImportBtn = () => {
        if(!this.state.data.brandId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.brandId',
                defaultMessage: '请先选择品牌'
            }));
        if(!this.state.data.dealerId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.dealerId',
                defaultMessage: '请先选择总代'
            }));
        if(!this.state.data.partOrderTypeId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.partOrderTypeId',
                defaultMessage: '请先选择订单类型'
            }));
        if(!this.state.data.transportType)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.transportType',
                defaultMessage: '请先选择运输方式'
            }));
        this.setState({showImportPanel: true});
    }
    onImportChange = records => {
        if(records.payload) {
            const retailDetails = this.state.details || [];
            records.payload.content.forEach(r => {
                const index = retailDetails.findIndex(v => v.partId === r.id);
                if(index === -1)
                    retailDetails.push({
                        partId: r.id,
                        partCode: r.code,
                        partName: r.name,
                        unit: r.unit,
                        planQuantity: r.planQuantity,
                        price: r.price ? r.price : r.estimatedPrice,
                        minPackSize: r.minPackSize,
                        estimatedPrice: r.estimatedPrice,
                        quantity: r.quantity,
                        partReplacementCode: r.partReplacementCode,
                        isColor: r.isColor,
                        isType: r.isType,
                        isTransport: r.isTransport,
                        isDealerUser: this.props.isDealerUser
                    });
                else
                    retailDetails.splice(index, 1, {
                        partId: r.id,
                        partCode: r.code,
                        partName: r.name,
                        unit: r.unit,
                        planQuantity: r.planQuantity,
                        price: r.price ? r.price : r.estimatedPrice,
                        minPackSize: r.minPackSize,
                        estimatedPrice: r.estimatedPrice,
                        quantity: r.quantity,
                        partReplacementCode: r.partReplacementCode,
                        isColor: r.isColor,
                        isType: r.isType,
                        isTransport: r.isTransport,
                        isDealerUser: this.props.isDealerUser
                    });
            });
            this.setState({
                details: [...retailDetails],
                hasOperat: true,
                showImportPanel: false,
                isAlert: true
            });
        }
    }
    onCloseImportPanel = () => {
        this.setState({showImportPanel: false});
    }
    onClickAddBtn = () => {
        if(!this.state.data.brandId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.brandId',
                defaultMessage: '请先选择品牌'
            }));
        if(!this.state.data.dealerId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.dealerId',
                defaultMessage: '请先选择总代'
            }));
        if(!this.state.data.partOrderTypeId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.partOrderTypeId',
                defaultMessage: '请先选择订单类型'
            }));
        if(!this.state.data.transportType)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.transportType',
                defaultMessage: '请先选择运输方式'
            }));
        this.setState({showPartMultiSelectPanel: true});
    }
    onSelectDealer = dealer => {
        this.getPartSaleOrder({
            ...this.state.data,
            dealerId: dealer.id
        });
        this.setState({
            data: Object.assign({}, this.state.data, {
                dealerId: dealer.id,
                dealerCode: dealer.code,
                dealerName: dealer.name,
                country: dealer.countryName,
                currency: dealer.currency
            })
        });
    }
    onConfirmNo = () => {
        this.setState({
            isAlert: false
        });
    }
    onConfirmYes = () => {
        this.setState({
            isLoading: true
        });
        partReplacementQuery({
            brandId: this.state.data.brandId,
            dealerId: this.state.data.dealerId,
            partReplacementCode: this.state.details.map(m => m.partReplacementCode)
        })
            .then(res => {
                if(res.ok) {
                    const tmp = this.state.details.filter(v => !res.data.some(o => o.code === v.partReplacementCode));
                    res.data.forEach(r => {
                        const index = tmp.findIndex(v => v.partId === r.id);
                        if(index === -1) {
                            const oldPart = this.state.details.find(v => v.partReplacementCode === r.code);
                            tmp.push({
                                partId: r.id,
                                partCode: r.code,
                                partName: r.name,
                                unit: r.unit,
                                planQuantity: r.minPackSize,
                                price: r.price ? r.price : r.estimatedPrice,
                                minPackSize: r.minPackSize,
                                estimatedPrice: r.estimatedPrice,
                                quantity: r.quantity,
                                partReplacementCode: r.partReplacementCode,
                                isType: r.isType,
                                isTransport: r.isTransport,
                                isDealerUser: this.props.isDealerUser,
                                oldPartId: oldPart.partId
                            });
                        }
                    });
                    this.setState({
                        details: [...tmp]
                    });
                }
                this.setState({
                    isLoading: false
                });
            });
    }
    onClickDetailExport = () => {
        this.props.onClickDetailExport(this.state.details);
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading, partOrderTypeCode} = this.state;
        const currentSelectRowkeys = details.map(item => item.partId);
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        const validatePartOrderType = !data.partOrderTypeId && this.state.validate ? 'error' : null;
        const validatePaymentType = !data.paymentType && this.state.validate ? 'error' : null;
        const validatePartOrderPriceTerms = !data.partOrderPriceTerms && this.state.validate ? 'error' : null;
        const validateReceivedCompany = !data.receivedCompany && this.state.validate ? 'error' : null;
        const validateReceivedTelephone = !data.receivedTelephone && this.state.validate ? 'error' : null;
        const validateReceivedPerson = !data.receivedPerson && this.state.validate ? 'error' : null;
        const validateReceivedPersonPhone = !data.receivedPersonPhone && this.state.validate ? 'error' : null;
        const validateReceivedAddress = !data.receivedAddress && this.state.validate ? 'error' : null;
        const validateReceivedPort = !data.receivedPort && this.state.validate ? 'error' : null;
        const validateTransportType = !data.transportType && this.state.validate ? 'error' : null;
        const validateBrandId = !data.brandId && this.state.validate ? 'error' : null;
        const validateDealer = !data.dealerId && this.state.validate ? 'error' : null;
        const validateAccount = !data.account && this.state.validate ? 'error' : null;
        const validateCarier = !data.carier && this.state.validate ? 'error' : null;
        const validateRemark = data.remark && data.remark.length > 100 && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.add, this.props.permissions) || !hasPermissions(PERMISSION.update, this.props.permissions) ||
        !hasPermissions(PERMISSION.assistAdd, this.props.permissions) || !hasPermissions(PERMISSION.assistUpdate, this.props.permissions);
        if(this.props.initEnum.brands.length === 1 && !this.props.id) {
            data.brandId = this.props.initEnum.brands[0].value;
            data.brandCode = this.props.initEnum.brands[0].text;
        }
        if(!this.props.id && this.props.isDealerUser) {
            data.dealerId = this.props.enterprise.id;
            data.dealerCode = this.props.enterprise.code;
            data.dealerName = this.props.enterprise.name;
            data.country = this.props.enterprise.country;
            data.currency = this.props.enterprise.currency;
        }
        let totalNumber = 0;
        let totalKind = 0;
        let totalPrice = 0;
        if(this.state.details) {
            totalKind = this.state.details.length;
            this.state.details.forEach(d => {
                totalNumber += (d.planQuantity);
                totalPrice += (d.planQuantity * d.price);
            });
        }
        const queryCondition = {
            brandId: data.brandId
        };
        const dealerComp = data.brandId ? (<DealerSelectPanel
            allowClear={false}
            value={dealerInfo}
            getDealerSimple={getDealersQuickly}
            getDealers={getDealers}
            conditions={queryCondition}
            onSelect={this.onSelectDealer} />) : (<TextInput name="dealerId"
            value={''} disabled={true} placeholder={this.props.intl.formatMessage({
                id: 'newPanel.dealerComp.placeholder',
                defaultMessage: '请先选择品牌'
            })} />);
        const colums = [{
            title: formatMessage({
                id: 'newPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
            width: 500,
            render: (text, record) => <div>
                {text}
                {record.partReplacementCode && <Tag color="#f50">{formatMessage({
                    id: 'newPanel.column.partReplacementCode',
                    defaultMessage: '存在替换件'
                })}</Tag>}
                {record.isType && <Tag color="#f50">{formatMessage({
                    id: 'newPanel.column.isType',
                    defaultMessage: '订单类型'
                })}</Tag>}
                {record.isTransport && <Tag color="#f50">{formatMessage({
                    id: 'newPanel.column.isTransport',
                    defaultMessage: '运输方式'
                })}</Tag>}
            </div>
        }, {
            title: formatMessage({
                id: 'newPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
            render: text => <Ellipsis tooltip fullWidthRecognition length={60}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'newPanel.column.minPackSize',
                defaultMessage: '最小包装数'
            }),
            width: 100,
            dataIndex: 'minPackSize',
        }, {
            title: formatMessage({
                id: 'newPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            width: 100,
            render: text => formatAmount(text)
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'newPanel.column.planQuantity',
                defaultMessage: '订购数量'
            })}</span>,
            dataIndex: 'planQuantity',
            width: 100,
            render: (text, record) => {
                const validate = (!text || text === undefined) || text === 0 ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <LocalizeInputNumber
                            min={0}
                            id={record.partId}
                            precision={0}
                            value={text} onBlur={this.onUpdateQuantity}/>
                    </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.quantity',
                defaultMessage: '库存数量'
            }),
            dataIndex: 'quantity',
            width: 100,
            render: text => text >= 5 ? formatMessage({
                id: 'newPanel.column.quantityYes',
                defaultMessage: '有'
            }) : formatMessage({
                id: 'newPanel.column.quantityUn',
                defaultMessage: '无'
            })
        }, {
            title: details && details.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'newPanel.column.allDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'newPanel.column.empty',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : <a>{formatMessage({
                    id: 'newPanel.column.empty',
                    defaultMessage: '清空'
                })}</a>,
            dataIndex: 'partId',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'newPanel.column.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        
        const message = (
            <Row>
                <Col span={5} className={styles.message}>{formatMessage({
                    id: 'newPanel.alert.message',
                    defaultMessage: '备件存在替换件，是否修改为替换件'
                })}</Col>
                <Col span={18} className={styles.confirmBtnStyle}>
                    <Button size="small" type="primary" onClick={this.onConfirmYes}>
                        {formatMessage({
                            id: 'btn.yes',
                            defaultMessage: '是'
                        })}
                    </Button>
                    <Button size="small" type="primary" onClick={this.onConfirmNo}>
                        {formatMessage({
                            id: 'btn.no',
                            defaultMessage: '否'
                        })}
                    </Button>
                </Col>
            </Row>
        );
        const warningmessage = (
            <div>
                <Row>
                    <Col className={styles.message}>{formatMessage({
                        id: 'newPanel.alert.message1',
                        defaultMessage: '红色高亮 + 编号后面的标签 ‘订单类型’，表示该条清单不满足 订单类型的提报属性'
                    })}</Col>
                </Row>
                <Row>
                    <Col className={styles.message}>{formatMessage({
                        id: 'newPanel.alert.message2',
                        defaultMessage: '红色高亮 + 编号后面的标签 ‘运输方式’，表示该条清单不满足 运输方式的提报属性'
                    })}</Col>
                </Row>
                <Row>
                    <Col className={styles.message}>{formatMessage({
                        id: 'newPanel.alert.message3',
                        defaultMessage: '蓝色高亮，表示导入的数据自动向上取最小包装的整数倍'
                    })}</Col>
                </Row>
            </div>
            
        );
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'newPanel.column.common',
                        defaultMessage: '基础信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.code',
                                        defaultMessage: '订单编号'
                                    })}
                                    {...FORM_OPTIONS.item} >
                                        <Input placeholder={formatMessage({
                                            id: 'newPanel.operation.notGenerate',
                                            defaultMessage: '尚未生成'
                                        })} value={data.code} disabled />
                                    </FormItem>
                                </Col>
                                {
                                    this.props.initEnum.brands.length !== 1 &&
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'newPanel.operation.brandId',
                                                defaultMessage: '品牌'
                                            })}
                                            {...FORM_OPTIONS.item}
                                            validateStatus={validateBrandId}
                                            required>
                                            <WrappedSelect
                                                name="brandId"
                                                options={this.props.initEnum.brands}
                                                value={data.brandId}
                                                onChange={this.onChangeBrand} />
                                        </FormItem>
                                    </Col>
                                }
                                <Col {...FORM_OPTIONS.col}>
                                    {this.props.id || this.props.isDealerUser ? (
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'newPanel.form.dealerId',
                                                defaultMessage: '总代'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <span className="value-font">({data.dealerCode}) {data.dealerName}</span>
                                        </FormItem>
                                    ) : (
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'newPanel.form.dealerId',
                                                defaultMessage: '总代'
                                            })}
                                            {...FORM_OPTIONS.item}
                                            validateStatus={validateDealer}
                                            required>
                                            {dealerComp}
                                        </FormItem>
                                    )}
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.customerOrderCode',
                                        defaultMessage: '客户订单编号'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="customerOrderCode"
                                            value={data.customerOrderCode}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.partOrderTypeId',
                                            defaultMessage: '订单类型'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validatePartOrderType}
                                        required>
                                        {this.props.id ? data.partOrderTypeName : <WrappedSelect
                                            name="partOrderTypeId"
                                            value={data.partOrderTypeId}
                                            options={this.props.initEnum.partSaleOrderTypes}
                                            onChange={this.onChangePartOrderType} />}
                                        
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.transportType',
                                            defaultMessage: '运输方式'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateTransportType}
                                        required>
                                        {data.partOrderTypeId ? <WrappedSelect
                                            disabled={partOrderTypeCode === 'VOR'}
                                            name="transportType"
                                            value={data.transportType}
                                            // eslint-disable-next-line no-nested-ternary
                                            options={partOrderTypeCode === 'Emergency' ? transportTypeOneList : (partOrderTypeCode === 'Normal' || partOrderTypeCode === 'Quarterly' ? transportTypeNormalList : transportTypeList)}
                                            onChange={this.onChangeTransportType} /> : <WrappedSelect
                                            disabled={false}
                                            allowClear
                                            name="transportType"
                                            value={data.transportType}
                                            options={transportTypeList}
                                            onChange={this.onChangeTransportType} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem className={styles.multiLabel} label={formatMessage({
                                        id: 'newPanel.operation.partOrderPlanCode',
                                        defaultMessage: '需求计划单号'
                                    })} {...FORM_OPTIONS.item}>
                                        <SearchInput
                                            disabled={true}
                                            value={data.partOrderPlanCode}
                                            id={data.partOrderPlanId}
                                            onClickSearchBtn={this.onClickPartOrderPlan} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.country',
                                        defaultMessage: '国家'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.paymentType',
                                            defaultMessage: '付款方式'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validatePaymentType}
                                        required>
                                        <WrappedSelect
                                            allowClear
                                            name="paymentType"
                                            value={data.paymentType}
                                            options={paymentTypeList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.partOrderPriceTerms',
                                            defaultMessage: '价格条款'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validatePartOrderPriceTerms}
                                        required>
                                        <WrappedSelect
                                            allowClear
                                            name="partOrderPriceTerms"
                                            value={data.partOrderPriceTerms}
                                            options={partOrderPriceTermsList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                {
                                    data.partOrderPriceTerms === partOrderPriceTerms.FCA &&
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'newPanel.operation.account',
                                            defaultMessage: '到付账号'
                                        })} {...FORM_OPTIONS.item}
                                        validateStatus={data.partOrderPriceTerms === partOrderPriceTerms.FCA ? validateAccount : null}
                                        required={data.partOrderPriceTerms === partOrderPriceTerms.FCA}>
                                            <TextInput
                                                name="account"
                                                value={data.account}
                                                onBlur={this.onChange} />
                                        </FormItem>
                                    </Col>
                                }
                                {
                                    (data.partOrderPriceTerms === partOrderPriceTerms.FCA ||
                                        data.partOrderPriceTerms === partOrderPriceTerms.FOB ||
                                        data.partOrderPriceTerms === partOrderPriceTerms.EXW) &&
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'newPanel.operation.carier',
                                            defaultMessage: '指定货代'
                                        })} {...FORM_OPTIONS.item}
                                        validateStatus={(data.partOrderPriceTerms === partOrderPriceTerms.FCA ||
                                            data.partOrderPriceTerms === partOrderPriceTerms.FOB ||
                                            data.partOrderPriceTerms === partOrderPriceTerms.EXW) ? validateCarier : null}
                                        required={data.partOrderPriceTerms === partOrderPriceTerms.FCA ||
                                        data.partOrderPriceTerms === partOrderPriceTerms.FOB ||
                                        data.partOrderPriceTerms === partOrderPriceTerms.EXW}>
                                            <TextInput
                                                name="carier"
                                                value={data.carier}
                                                onBlur={this.onChange} />
                                        </FormItem>
                                    </Col>
                                }
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.receivedCompany',
                                        defaultMessage: '收货方'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateReceivedCompany}
                                    required>
                                        <TextInput
                                            name="receivedCompany"
                                            value={data.receivedCompany}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.receivedTelephone',
                                        defaultMessage: '收货方电话'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateReceivedTelephone}
                                    required>
                                        <TextInput
                                            name="receivedTelephone"
                                            value={data.receivedTelephone}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.receivedPerson',
                                        defaultMessage: '收货联系人'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateReceivedPerson}
                                    required>
                                        <TextInput
                                            name="receivedPerson"
                                            value={data.receivedPerson}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.receivedPersonPhone',
                                        defaultMessage: '收货人联系电话'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateReceivedPersonPhone}
                                    required>
                                        <TextInput
                                            name="receivedPersonPhone"
                                            value={data.receivedPersonPhone}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.receivedPort',
                                        defaultMessage: '目的港口'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateReceivedPort}
                                    required>
                                        <TextInput
                                            name="receivedPort"
                                            value={data.receivedPort}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.shipmentPort',
                                        defaultMessage: '发运港口'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="shipmentPort"
                                            value={data.shipmentPort}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.receivedAddress',
                                        defaultMessage: '收货地址'
                                    })} {...FORM_ROW_OPTIONS.item}
                                    validateStatus={validateReceivedAddress}
                                    required>
                                        <TextInput
                                            type="textarea"
                                            name="receivedAddress"
                                            value={data.receivedAddress}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item} validateStatus={validateRemark}>
                                        <TextInput
                                            type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'newPanel.operation.detail',
                            defaultMessage: '订单清单'
                        })}
                        extra={<div>
                            {
                                (details.some(v => v.partReplacementCode !== null) || details.some(v => v.isType === true) || details.some(v => v.isTransport === true)) &&
                                <Export key={'export'} exportRequest={() => this.props.onClickDetailExport(details)} />
                            }
                            <Button
                                size="small"
                                onClick={this.onClickImportBtn}>
                                {formatMessage({
                                    id: 'newPanel.operation.import',
                                    defaultMessage: '导入清单'
                                })}
                            </Button>
                            <Button
                                size="small"
                                onClick={this.onClickAddBtn}>
                                {formatMessage({
                                    id: 'newPanel.operation.newDetail',
                                    defaultMessage: '新增清单'
                                })}
                            </Button>
                        </div>}>
                        {
                            details.length > 0 && <Alert
                                className={styles.alertStyle}
                                showIcon
                                type="warning"
                                message={warningmessage} />
                        }
                        {
                            (details.some(v => v.partReplacementCode !== null) && this.state.isAlert) && <Alert
                                className={styles.alertStyle}
                                showIcon
                                type="info"
                                message={message} />
                        }
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            loading={this.state.isLoading}
                            rowKey="partId"
                            dataSource={details}
                            rowClassName={this.setRowClassName}
                            pagination={false}
                            footer={() => <DescriptionList><Description term={formatMessage({
                                id: 'newPanel.operation.totalNumber',
                                defaultMessage: '订购量汇总'
                            })}>{totalNumber}
                            </Description><Description term={formatMessage({
                                id: 'newPanel.operation.totalKind',
                                defaultMessage: '品种汇总'
                            })}>{totalKind}
                            </Description>
                            <Description term={formatMessage({
                                id: 'newPanel.operation.totalPrice',
                                defaultMessage: '金额汇总'
                            })}>{formatAmount(totalPrice)}
                            </Description></DescriptionList>}
                            scroll={{
                                x: 'max-content',
                                y: 800
                            }}
                            size="small"
                            bordered={true}/>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSave',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                    {
                        this.state.showPartMultiSelectPanel &&
                        <PartMultiSelectPanel
                            currentSelectRowkeys={currentSelectRowkeys}
                            partOrderTypeId={data.partOrderTypeId}
                            transportType={data.transportType}
                            brandId={data.brandId}
                            dealerId={data.dealerId}
                            selectKey={data.id}
                            onCancel={this.onClosePartMultiSelectPanel}
                            onSelect={this.onSelectPart} />
                    }
                    {
                        this.state.showImportPanel &&
                        <ImportPanel
                            partOrderTypeId={data.partOrderTypeId}
                            transportType={data.transportType}
                            brandId={data.brandId}
                            dealerId={data.dealerId}
                            selectKey={data.warehouseId}
                            onCancel={this.onCloseImportPanel}
                            onImportChange={this.onImportChange} />
                    }
                    {
                        this.state.showPartOrderPlan &&
                        <PartOrderPlanPanel
                            partOrderTypeId={data.partOrderTypeId}
                            transportType={data.transportType}
                            dealerCode={data.dealerCode}
                            dealerName={data.dealerName}
                            brandCode={data.brandCode}
                            brandId={data.brandId}
                            dealerId={data.dealerId}
                            selectKey={data.id}
                            onCancel={this.onClosePartOrderPlan}
                            onSelect={this.onSelectPartOrderPlan} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickDetailExport: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    enterprise: PropTypes.object,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onSubmit,
    detailExport
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const partSaleOrderTypes = initData.partSaleOrderTypes ? initData.partSaleOrderTypes.map(item => ({
            text: `${item.typeName}`,
            value: item.id
        })) : [];
        return {
            brands,
            partSaleOrderTypes
        };
    }
);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getEnterprise = selectorFactory(['page', 'domainData', 'initData', 'enterprise']);
const mapStateToProps = (state, props) => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    initEnum: getinitEnumData(state),
    enterprise: getEnterprise(state),
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details) => dispatch(onSubmit(data, details)),
    onClickDetailExport: details => dispatch(detailExport(details)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
